import { existsSync, readFileSync, writeFileSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from 'url';

function getRootDir () {
  const __filename = fileURLToPath(import.meta.url);
  const __dirname = dirname(__filename);
  return join(__dirname , '..');
}
function isExistDist () {
  const rootDir = getRootDir();
  return existsSync(join(rootDir , './dist'));
}

function getDistDir () {
  const rootDir = getRootDir();
  return join(rootDir , './dist');
}

function generateConfig () {
  const rootDir = getRootDir();
  const content = readFileSync(join(rootDir , '.env.production') , 'utf-8');
  if (content.trim()) {
    const configList = content.split('\n');
    let contentStr = '';
    configList.forEach((config , index) => {
      const [ key , value ] = config.split('=');
      contentStr += `${key}: ${JSON.stringify(value)}${index < configList.length - 1 ? ',\n' : ''}\t`;
    });
    return `window.config = {\n\t${contentStr}\n}`;
  }
  return `window.config = {};`
}

function writeScript () {
  const rootDir = getRootDir();
  const filename = join(rootDir , './dist/index.html');
  let content = readFileSync(filename , 'utf-8');
  content = content.replace(/<\/title>/ , `</title>\n\t\t<script type="module" crossorigin src="/config.js"></script>`);
  writeFileSync(filename , content , 'utf-8');
}

if (isExistDist()) {
  const distDir = getDistDir();
  writeFileSync(join(distDir , './config.js') , generateConfig());
  // 读取index.html，将config.js写入到script标签中
  writeScript();
}